/**
 * 一些公用的功能性api
 * Created by dongchen on 16/5/19.
 */
var express = require('express');
var router = express.Router();
var co = require('co');
var coRequest = require('co-request');
var commonUtils = require('../lib/commonUtils');
var iconv = require('iconv-lite');

router.get('/api/v1/mobile/locale', function(req, res){
    function * handler (){
        var
            response, body,
            mobile = req.query.mobile,
            queryUrl = 'https://tcc.taobao.com/cc/json/mobile_tel_segment.htm',
            queryParam = {
                tel : mobile
            },
            url = commonUtils.buildUrl(queryUrl, queryParam);
        response = yield coRequest.get({url : url, encoding : null});
        if(response.statusCode == 200){
            var body = eval(iconv.decode(response.body, 'GBK'));

            return {
                province : body.province,
                sp : body.catName,
                subSp : body.carrier
            };
        }else{
            throw `request : ${url} \n status : ${response.statusCode}`;
        }
    }

    commonUtils.coHandler(handler, res);
});

module.exports = router;